#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from shared.helper import render_to_response
from time import strftime, gmtime

from usermanagement.forms import LoginForm
from filemanagement.models import *

import os
from django.core.servers.basehttp import FileWrapper
from django.contrib.auth.decorators import login_required
from django.conf import settings
from filemanagement.path import Path

import magic

@login_required
def index(request, path=''):

    path = __clean_path(path)
    if os.path.isfile(path): # if the path is an file: provide download!
        return __download(path)

    dirs = []
    files = []
    # collect files and dirs
    for fn in os.listdir(path):
        filepath = os.path.join(path, fn)
        relfilepath = os.path.relpath(filepath, settings.DOWNLOAD_ROOT)
        lastmodified = strftime('%Y/%m/%d %H:%M:%S', gmtime(os.path.getmtime(filepath)))
        if os.path.isdir(filepath):
            dirs.append(Path(relfilepath, lastmodified))
        if os.path.isfile(filepath):
            files.append(Path(relfilepath, lastmodified))
    
    # sort the lists alphanumerically
    dirs.sort(key=lambda x: x.name.lower())
    files.sort(key=lambda x: x.name.lower())
    
    relpath = os.path.relpath(path, settings.DOWNLOAD_ROOT)
    breadcrumbs = []
    while relpath != '' :
        tpath = Path(relpath, None)
        if tpath.name != '.':
            breadcrumbs.insert(0,Path(relpath, None))
            relpath = os.path.split(relpath)[0]
        else:
            break

    
    return render_to_response(request, 'filemanagement/index.html', {'dirs': dirs, 'files': files, 'breadcrumbs': breadcrumbs})

def __download(path):
    """                                                                         
    Send a file through Django without loading the whole file into              
    memory at once. The FileWrapper will turn the file object into an           
    iterator for chunks of 8KB.                                                 
    """
    wrapper = FileWrapper(file(path))
    
    m = magic.open(magic.MAGIC_MIME)
    m.load()
    
    response = HttpResponse(wrapper, content_type=m.file(path)) # dynamically load mimetype to responce
    response['Content-Length'] = os.path.getsize(path)
    return response
    
def __clean_path(path):
    """
    Cleans path from "../" and other stuff that could cause an exploitation and makes it absolute
    """
    path = os.path.join(settings.DOWNLOAD_ROOT, path)
    path = os.path.realpath(path)
    if os.path.commonprefix([settings.DOWNLOAD_ROOT, path]) != settings.DOWNLOAD_ROOT: #TODO: Safe?
        return settings.DOWNLOAD_ROOT
    return path
